package com.cloudbroker.bcs.platform.ltb.middle.bizservice.impl;

import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.configure.ConfigUtil;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.csvc.lightinvesting.api.t2service.LedSecT2Service;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.cashTransactions.CompayApplyForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.cashTransactions.CompayConfirmForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.CompayApplyVo;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.CompayConfirmVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.pay.PayBizService;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.pay.back.PayApplyBack;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.pay.back.PayConfirmBack;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.pay.vo.PayApplyForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.pay.vo.PayConfirmForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.back.DongbeiPayHtmlBack;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.vo.DongbeiPayHtmlForm;
import com.cloudbroker.bcs.platform.ltb.common.payUtil.HttpUtils;
import com.cloudbroker.bcs.platform.ltb.common.payUtil.bean.OrderRequest;
import com.cloudbroker.bcs.platform.ltb.middle.util.MD5Util;
import com.thinkive.openservice.api.TKOpenServiceClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by daibd19671 on 2016/10/28.
 */
@Service
public class PayBizServiceImpl implements PayBizService {

    @Resource
    private LedSecT2Service ledSecT2Service;

    private Logger logger = LoggerFactory.getLogger(PayBizServiceImpl.class);
    @Override
    public PayApplyBack compay_apply(PayApplyForm form) {
        //后台获取流水号
        CompayApplyForm compayApplyForm = new CompayApplyForm();
        compayApplyForm.setCombi_code(form.getCombi_code());
        compayApplyForm.setAdviser_id(form.getAdviser_id());
        compayApplyForm.setCompay_channel(form.getCompay_channel());
        compayApplyForm.setPartner_id("1262260201");
        compayApplyForm.setMoney_type("CNY");
        compayApplyForm.setOccur_balance(form.getOccur_balance());
        compayApplyForm.setChannel_id(form.getChannel_id());
        compayApplyForm.setRemark(form.getRemark());
        compayApplyForm.setOp_branch_no(form.getOp_branch_no());
        compayApplyForm.setOp_entrust_way(form.getOp_entrust_way());
        compayApplyForm.setOp_station(form.getOp_station());
        compayApplyForm.setBranch_no(form.getBranch_no());
        compayApplyForm.setPassword(form.getPassword());
        compayApplyForm.setPassword_type(form.getPassword_type());
        compayApplyForm.setUser_token(form.getUser_token());
        CompayApplyVo compayApplyVo = ledSecT2Service.func_compay_apply(compayApplyForm);
//        CompayApplyVo compayApplyVo = new CompayApplyVo();
        //云融获取交易参数
        OrderRequest request = new OrderRequest();
        request.setPartner_id("1262260201");
        request.setPartner_serial_no(compayApplyVo.getPartner_serial_no());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(new Date());
        request.setPartner_trans_date(date.substring(0,8));
        request.setPartner_trans_time(date.substring(8,date.length()));
//        request.setProd_name();
        request.setCurrency_code("CNY");
        request.setOccur_balance(String.valueOf(form.getOccur_balance()));
//        request.setSummary();
        request.setChannel_id(form.getChannel_id());
//        request.setPickup_url(ConfigUtil.get("func_pay_result_address"));
//        request.setReceive_url();
//        request.setPartner_userid();
        request.setSendercomp_id("1262260201");
        request.setTargetcomp_id("91000");
        String receiveUrl = ConfigUtil.get("func_pay_result_address");
        if(!StringUtil.isEmpty(receiveUrl)){
            request.setReceive_url(receiveUrl);
        }else{
            return VOUtil.genErrorResult(HSBCPSErrorCodes.CombinationErrorInfo.APPLY_PAY_PROCEED_ERR,
                    PayApplyBack.class);
        }

        String pay_parameter = null;
        try {
            pay_parameter = HttpUtils.proceed(request,HttpUtils.epay_wallet_pay);
        } catch (Exception e) {
            e.printStackTrace();
            return VOUtil.genErrorResult(HSBCPSErrorCodes.CombinationErrorInfo.APPLY_PAY_PROCEED_ERR,
                    PayApplyBack.class);
        }

        JSONObject parameterJson = JSONObject.parseObject(pay_parameter);
        Object paramater = parameterJson.get("view");
        if(paramater== null || StringUtil.isEmpty(paramater.toString())){
            logger.error(parameterJson.toString());
            return VOUtil.genErrorResult(HSBCPSErrorCodes.CombinationErrorInfo.APPLY_PAY_PARAMETER_ERR,
                    PayApplyBack.class);
        }
        PayApplyBack payApplyBack = new PayApplyBack();
        payApplyBack.setPay_parameter(pay_parameter);
        return VOUtil.setSuccessResult(payApplyBack);
    }

    @Override
    public PayConfirmBack result_apply(PayConfirmForm form) {
        try {
            CompayConfirmForm compayConfirmForm = new CompayConfirmForm();
            compayConfirmForm.setPartner_id(form.getPartner_id());
            compayConfirmForm.setPartner_serial_no(form.getPartner_serial_no());
            compayConfirmForm.setHsepay_order_no(form.getHsepay_order_no());
            compayConfirmForm.setPay_status(form.getPay_status());
            compayConfirmForm.setError_msg(form.getError_msg());
            CompayConfirmVo compayConfirmVo = ledSecT2Service.func_compay_confirm(compayConfirmForm);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            PayConfirmBack payConfirmBack = new PayConfirmBack();
            payConfirmBack.setResult("success");
            return VOUtil.setSuccessResult(payConfirmBack);
        }
    }




    @Override
    public DongbeiPayHtmlBack dongbei_pay_html(DongbeiPayHtmlForm form) {
        //后台获取流水号
        CompayApplyForm compayApplyForm = new CompayApplyForm();
//        compayApplyForm.setCombi_code(form.getCombi_code());
//        compayApplyForm.setAdviser_id(form.getAdviser_id());
        compayApplyForm.setCompay_channel("0");
        compayApplyForm.setPartner_id(form.getSendercomp_id());
        compayApplyForm.setMoney_type("CNY");
        compayApplyForm.setOccur_balance(Double.parseDouble(form.getTot_price()));
//        compayApplyForm.setChannel_id(form.getChannel_id());
//        compayApplyForm.setRemark(form.getRemark());
        compayApplyForm.setOp_branch_no(form.getOp_branch_no());
        compayApplyForm.setOp_entrust_way(form.getOp_entrust_way());
        compayApplyForm.setOp_station(form.getOp_station());
        compayApplyForm.setBranch_no(form.getBranch_no());
        compayApplyForm.setPassword(form.getPassword());
        compayApplyForm.setPassword_type(form.getPassword_type());
        compayApplyForm.setUser_token(form.getUser_token());
//        CompayApplyVo compayApplyVo = ledSecT2Service.func_compay_apply(compayApplyForm);
//        if(!VOUtil.isSuccess(compayApplyVo)){
//            return VOUtil.genBGErrorResult(compayApplyVo.getError_no(),compayApplyVo.getError_info(),DongbeiPayHtmlBack.class);
//        }
        String tot_price = form.getTot_price();
//        String order_id = compayApplyVo.getPartner_serial_no();
        String order_id = "1234567890";
        String order_type = "02";
        String cn = "02";
        String product_name = "测试";
        String order_price = form.getTot_price();
        String num = "1";
        String user_name = form.getUser().getUser_name();
        String mobile = form.getUser().getMobile();
        String token = MD5Util.encrypt(  cn + order_type + order_id +   tot_price + "000686cxcs").toLowerCase();
        Map<String,String> param = new HashMap<String,String>(3);
        param.put("tot_price",tot_price);
        param.put("order_id",order_id);
        param.put("order_type",order_type);
        param.put("cn",cn);
        param.put("product_name",product_name);
        param.put("order_price",order_price);
        param.put("num",num);
        param.put("user_name",user_name);
        param.put("mobile",mobile);
        param.put("token",token);
        String resultStr = TKOpenServiceClient.sendData("200011", param);
        System.out.println(param.toString());
        System.out.println(resultStr);
        JSONObject resultJson = JSONObject.parseObject(resultStr);
        if(!resultJson.get("error_no").toString().equals("0")){
            VOUtil.genBGErrorResult(resultJson.getString("error_no"),
                    resultJson.getString("error_info"),DongbeiPayHtmlBack.class);
        }
        JSONObject result = resultJson.getJSONArray("results").getJSONObject(0);
        DongbeiPayHtmlBack dongbeiPayHtmlBack = new DongbeiPayHtmlBack();
        dongbeiPayHtmlBack.setPay_html(result.getString("pay_html"));
        dongbeiPayHtmlBack.setTot_price(result.getString("tot_price"));
        dongbeiPayHtmlBack.setCn(result.getString("cn"));
        dongbeiPayHtmlBack.setOrder_type(result.getString("order_type"));
        dongbeiPayHtmlBack.setOrder_id(result.getString("order_id"));
        return VOUtil.setSuccessResult(dongbeiPayHtmlBack);
    }


    public static void main(String[] args) {
        PayBizServiceImpl p = new PayBizServiceImpl();
        URL url = p.getClass().getClassLoader().getResource("test.pfx");
        System.out.println(url.getPath());
    }


}
